package servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class Login extends HttpServlet {
    private static final long serialVersionUID = -2422894297676813288L;
    private ServletContext app;

    @SuppressWarnings("unchecked")
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HashMap<String, String> users = (HashMap<String, String>) app.getAttribute("users");
        Collection<String> sessIds = users.values();
        HttpSession sess = req.getSession();
        String sessId = sess.getId();
        // 如果会话id集合中不包含指定会话id
        if (!sessIds.contains(sessId)) {
            sess.invalidate();
            resp.sendRedirect("entrance");
        }
    }

    /**
     * 每次提交post请求后，如果请求指定参数不为空，那么
     * <p>如果此参数已经是上下文的users映射中的一个键，那么更新键对应的值，即会话id
     * <p>如果此参数不是users映射中的键，那么将上下文中的online属性值增加1
     * <p>更新会话的name属性值
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("your-name");
        // 如果请求传递的your-name参数的值不为空
        if (name != null && !name.equals("")) {
            @SuppressWarnings("unchecked")
            HashMap<String, String> users = (HashMap<String, String>) app.getAttribute("users");
            Set<String> names = users.keySet();
            // 如果names中不包含name
            if (!names.contains(name)) {
                app.setAttribute("online", (int) app.getAttribute("online") + 1);
            }
            HttpSession sess = req.getSession();
            // 每次post请求会更新users中name键对应的值。即：如果name已存在于names，该name对应的会话id将被替换
            users.put(name, sess.getId());
            app.setAttribute("users", users);
            sess.setAttribute("name", name);
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        super.service(req, resp);
        PrintWriter out = resp.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("<head><title>欢迎登录</title></head>");
        out.print("<body>");
        out.print("当前在线：" + app.getAttribute("online") + "名用户<br>");
        out.print("<a href='exit'>注销</a><br>");
        out.print("已登录用户名<br>");
        @SuppressWarnings("unchecked")
        HashMap<String, String> users = (HashMap<String, String>) app.getAttribute("users");
        Set<Map.Entry<String, String>> set = users.entrySet();
        for (Map.Entry<String, String> entry : set) {
            out.print(entry.getKey() + "<br>");
        }
        out.print("</body>");
        out.print("</html>");
    }

    @Override
    public void destroy() {
        System.out.println("销毁servlet");
        super.destroy();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("初始化servlet");
        super.init(config);
        app = config.getServletContext();
    }
}
